package ar.Location.Internet;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import ar.Location.PlaceObject.PlaceCategoryManager;
import ar.globals.Globals;

public class NetworkStateReceiver extends BroadcastReceiver {
	private static final String TAG = "NetworkStateReceiver";
	public static boolean isNetworkConnected = false;
	static boolean isInit = true;
	static float lat = -1;
	static float lng = -1;

	public void onReceive(Context context, Intent intent) {
		Log.d(TAG, "Network connectivity change");
		if (intent.getExtras() != null) {
			NetworkInfo ni = (NetworkInfo) intent.getExtras().get(
					ConnectivityManager.EXTRA_NETWORK_INFO);
			if (ni != null && ni.getState() == NetworkInfo.State.CONNECTED) {

				if (isNetworkConnected == false) {
					Log.d(TAG, "Network " + ni.getTypeName() + " connected");
					isNetworkConnected = true;
					if (Globals.LAT != null && Globals.LNG != null) {
						if (Globals.LAT.length() > 0
								&& Globals.LNG.length() > 0) {

							if (isInit) {

								isInit = false;

								lat = Float.parseFloat(Globals.LAT);
								lng = Float.parseFloat(Globals.LNG);

								if (!PlaceCategoryManager
										.isProcessingLoadListCategories()) {
									PlaceCategoryManager.loadListCategories(
											lat, lng, Globals.RADIUS);
								}

								if (!PlaceCategoryManager
										.isProcessingLoadListDataSources()) {
									PlaceCategoryManager.loadListDataSources(
											lat, lng, Globals.RADIUS);
								}
							} else {
								float nlat = Float.parseFloat(Globals.LAT);
								float nlng = Float.parseFloat(Globals.LNG);

								if (lat != nlat || lng != nlng) {

									if (!PlaceCategoryManager
											.isProcessingLoadListCategories()) {
										PlaceCategoryManager
												.loadListCategories(lat, lng,
														Globals.RADIUS);
									}

									if (!PlaceCategoryManager
											.isProcessingLoadListDataSources()) {
										PlaceCategoryManager
												.loadListDataSources(lat, lng,
														Globals.RADIUS);
									}
								}
							}
						}
					}
				}
			}
		}
		if (intent.getExtras().getBoolean(
				ConnectivityManager.EXTRA_NO_CONNECTIVITY, Boolean.FALSE)) {
			Log.d(TAG, "There's no network connectivity");
			if (isNetworkConnected) {
				isNetworkConnected = false;
			}
		}
	}
}
